package is.server.ui;

import is.common.interfaces.mvc.UserInterface;
import is.server.Locale;
import is.server.controller.session.local.LocalSessionThread;

import java.io.PrintStream;

/**
 * CLI functionality for use in command calls.
 *
 * @author aspr0
 *         Date: 02.04.12
 *         Time: 0:59
 */
public class Cli implements UserInterface
{
    private LocalSessionThread localSessionThread = new LocalSessionThread();

    public void activate()
    {
        localSessionThread.start();
    }

    public void deactivate()
    {
        localSessionThread.deactivate(); //console thread exits run() and console deactivates
        exposeInfoMsg(Locale.INFO_GOODBYE);
    }

    public void exposeInfoMsg(String msg, Object... subs)
    {
        printlnMsg(System.out, msg, subs);
    }

    public void exposeWarnMsg(String msg, Object... subs)
    {
        printlnMsg(System.out, msg, subs);
    }

    public void exposeErrMsg(String msg, Object... subs)
    {
        printlnMsg(System.err, msg, subs);
    }

    @Override
    public void exposeRows(int sectionNum, String[] header, String[][] rows)
    {
        for (String[] row : rows)
        {
            for (String entry : row)
            {
                System.out.print(entry + "\t");
            }
            System.out.println();
        }
    }

    @Override
    public void exposeConnectionEstablished()
    {
        exposeInfoMsg(Locale.INFO_ROOT_SESSION_STARTED);
    }

    @Override
    public void exposeConnectionBroken()
    {
        exposeInfoMsg("Goodbye");
    }

    public void printInvitation()
    {
        System.out.print(Locale.INVITATION_ROOT);
    }

    /**
     * Prints msg to specified PrintStream, optional parameters subs will be placed
     * instead %s markers in msg in order they are specified
     *
     * @param msg
     * @param subs
     */
    private void printlnMsg(PrintStream ps, String msg, Object... subs)
    {
        if (subs.length > 0)
        {
            ps.println(String.format(msg, subs));
        }
        else
        {
            ps.println(msg);
        }
    }
}
